<template>
  <div class="code-block" :class="{ 'is-collapsed': isCollapsed && shouldCollapse }">
    <div class="code-header">
      <div class="language-tag">
        <span class="language-icon">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M8.293 6.293a1 1 0 0 1 1.414 0l6 6a1 1 0 0 1 0 1.414l-6 6a1 1 0 0 1-1.414-1.414L13.586 12 8.293 6.707a1 1 0 0 1 0-1.414z"/>
          </svg>
        </span>
        <span class="language-name">{{ language }}</span>
      </div>
      <div class="code-actions">
        <span v-if="fileName" class="file-name">{{ fileName }}</span>
        <button class="copy-btn" @click="copyCode" :title="copyBtnTitle">
          <span class="copy-icon" :class="{ 'copied': copied }">
            <svg v-if="!copied" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
              <path fill="currentColor" d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
            </svg>
            <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
              <path fill="currentColor" d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
            </svg>
          </span>
          {{ copied ? '已复制' : '复制' }}
        </button>
      </div>
    </div>
    <div class="code-content" ref="codeContent">
      <div v-if="showLineNumbers" class="code-line-numbers">
        <div v-for="i in visibleLines" :key="i" class="line-number">{{ i }}</div>
      </div>
      <pre><code :class="codeClass" ref="codeEl">{{ code }}</code></pre>
    </div>
    <div v-if="shouldCollapse" class="code-footer">
      <button class="toggle-btn" @click="toggleCollapse">
        {{ isCollapsed ? '显示更多' : '收起代码' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css'; // 可以选择其他主题

const props = defineProps({
  code: {
    type: String,
    required: true
  },
  language: {
    type: String,
    default: 'plaintext'
  },
  fileName: {
    type: String,
    default: ''
  },
  showLineNumbers: {
    type: Boolean,
    default: true
  },
  maxLines: {
    type: Number,
    default: 15
  }
});

const codeEl = ref(null);
const codeContent = ref(null);
const copied = ref(false);
const isCollapsed = ref(false);
const lineCount = ref(0);

// 计算代码行数
const countLines = () => {
  if (props.code) {
    return props.code.split('\n').length;
  }
  return 0;
};

// 是否应该折叠
const shouldCollapse = computed(() => {
  return lineCount.value > props.maxLines;
});

// 可见行数
const visibleLines = computed(() => {
  if (isCollapsed.value && shouldCollapse.value) {
    return props.maxLines;
  }
  return lineCount.value;
});

// 语言类
const codeClass = computed(() => {
  return `language-${props.language}`;
});

// 复制按钮提示
const copyBtnTitle = computed(() => {
  return copied.value ? '已复制到剪贴板' : '复制代码';
});

// 复制代码
const copyCode = () => {
  navigator.clipboard.writeText(props.code).then(() => {
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  });
};

// 切换折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 高亮代码
const highlightCode = () => {
  if (codeEl.value) {
    hljs.highlightElement(codeEl.value);
  }
};

// 监听代码变化
watch(() => props.code, () => {
  lineCount.value = countLines();
  nextTick(() => {
    highlightCode();
  });
});

onMounted(() => {
  lineCount.value = countLines();
  highlightCode();
});
</script>

<style scoped>
.code-block {
  position: relative;
  background: #282c34;
  border-radius: 6px;
  margin: 16px 0;
  overflow: hidden;
  font-family: Consolas, Monaco, 'Courier New', monospace;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  background: rgba(0, 0, 0, 0.2);
  color: #abb2bf;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.language-tag {
  display: flex;
  align-items: center;
  gap: 6px;
}

.language-icon {
  display: flex;
  align-items: center;
}

.language-name {
  text-transform: uppercase;
  font-weight: 500;
}

.code-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-name {
  color: #e6e6e6;
  margin-right: 8px;
  font-style: italic;
}

.copy-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #abb2bf;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
}

.copy-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.copy-icon {
  display: flex;
  align-items: center;
}

.copy-icon.copied {
  color: #98c379;
}

.code-content {
  display: flex;
  overflow-x: auto;
  position: relative;
  
  /* 隐藏滚动条 - 各浏览器兼容 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* Webkit 浏览器（Chrome、Safari等）隐藏滚动条 */
.code-content::-webkit-scrollbar {
  display: none;
}

.code-line-numbers {
  user-select: none;
  text-align: right;
  color: #636d83;
  padding: 12px 8px;
  border-right: 1px solid #3e4451;
  background: rgba(0, 0, 0, 0.1);
  min-width: 40px;
}

.line-number {
  font-size: 12px;
  line-height: 1.5;
}

pre {
  margin: 0;
  padding: 12px 16px;
  overflow-x: auto;
  flex: 1;
  
  /* 隐藏滚动条 - 各浏览器兼容 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* Webkit 浏览器（Chrome、Safari等）隐藏滚动条 */
pre::-webkit-scrollbar {
  display: none;
}

code {
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
  tab-size: 2;
}

.code-footer {
  padding: 8px;
  text-align: center;
  background: rgba(0, 0, 0, 0.2);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.toggle-btn {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #abb2bf;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
}

.toggle-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.is-collapsed .code-content {
  max-height: calc(1.5em * v-bind('props.maxLines') + 24px);
  overflow-y: hidden;
}

/* 适配移动设备 */
@media (max-width: 768px) {
  .code-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .code-actions {
    width: 100%;
    justify-content: space-between;
  }
}
</style>